import { Injectable } from '@nestjs/common';
import { CreateAuthorInput } from './dto/create-author.input';
import { UpdateAuthorInput } from './dto/update-author.input';
import { HasuraService } from '../hasura.service';
import { Author } from './entities/author.entity';
import { AuthorVo } from './vo/author.vo';
import { generateUuid } from '../utils/uuid.utils';
import { Client, gql } from '@urql/core';

@Injectable()
export class AuthorsService {
  private client: Client;
  constructor(private readonly hasuraService: HasuraService) {}

  async create(createAuthorInput: CreateAuthorInput): Promise<Author> {
    const author: Author = {
      author_id: generateUuid(),
      author_name: createAuthorInput.author_name,
      birth_date: createAuthorInput.birth_date,
      country: createAuthorInput.country,
    };
    const mutation = `
      mutation InsertAuthor($objects: [authors_insert_input!]!) {
        insert_authors(objects: $objects) {
          returning {
            author_id
            author_name
            birth_date
            country
          }
        }
      }
    `;

    const variables = {
      objects: [author],
    };

    try {
      const result = await this.hasuraService
        .mutation(mutation, variables)
        .toPromise();
      return result.data.insert_authors.returning[0];
    } catch (error) {
      throw new Error('error');
    }
    return author;
  }

  async findAll(author_name: string | undefined): Promise<AuthorVo[]> {
    try {
      let query: string;
      let variables = {};

      if (author_name) {
        // 当 author_name 传入时，使用 _like 操作符进行模糊查询
        query = `
                query($author_name: String) {
                    authors(where: { author_name: { _like: $author_name } }) {
                        author_id
                        author_name
                        birth_date
                        country
                        books {
                            author_id
                            book_id
                            book_title
                            publication_year
                        }
                    }
                }
            `;
        variables = { author_name: `%${author_name}%` };
      } else {
        query = `
                query {
                    authors {
                        author_id
                        author_name
                        birth_date
                        country
                        books {
                            author_id
                            book_id
                            book_title
                            publication_year
                        }
                    }
                }
            `;
      }
      const result = await this.hasuraService
        .query(query, variables)
        .toPromise();

      if (result && result.data && result.data.authors) {
        return result.data.authors;
      } else {
        return [];
      }
    } catch (error) {
      console.error('Error fetching authors:', error);
      throw new Error('Failed to fetch authors');
    }
  }

  /**
   * 根据作者ID查询单个作者信息
   * @param id 作者的ID
   * @returns 单个作者信息
   */
  async findOne(author_id: string): Promise<AuthorVo | null> {
    try {
      const query = `
        query ($author_id: uuid!) {
        authors_by_pk(author_id: $author_id) {
          author_id
          author_name
          birth_date
          country
          books {
            author_id
            book_id
            book_title
            publication_year
          }
        }
      }
      `;

      const variables = { author_id };

      const result = await this.hasuraService
        .query(query, variables)
        .toPromise();

      // 检查查询结果是否包含数据
      if (result && result.data && result.data.authors_by_pk) {
        let author: AuthorVo | null = null;
        author = result.data.authors_by_pk;
        return author;
      } else {
        return null;
      }
    } catch (error) {
      // 处理查询过程中出现的错误
      console.error('获取作者时出错：', error);
      throw new Error('无法获取作者');
    }
  }

  async update(id: string, updateAuthorInput: UpdateAuthorInput): Promise<Author> {
    const mutation = `
      mutation updateAuthor($author_name: String, $birth_date: String, $country: String, $author_id: uuid) {
        update_authors(
          _set: { author_name: $author_name, birth_date: $birth_date, country: $country }
          where: { author_id: { _eq: $author_id } }
        ) {
          returning {
            author_id
            author_name
            birth_date
            country
          }
        }
      }
    `;

    const variables = {
      author_name: updateAuthorInput.author_name,
      birth_date: updateAuthorInput.birth_date,
      country: updateAuthorInput.country,
      author_id: id
    };

    try {
      const gqlMutation = gql`
        ${mutation}
      `;
      const result = await this.client
        .mutation(gqlMutation, variables)
        .toPromise();
      const updatedAuthor = result.data?.update_authors?.returning[0];
      if (!updatedAuthor) {
        throw new Error(`Author with id ${id} not found or update failed.`);
      }
      return updatedAuthor;
    } catch (error) {
      throw new Error('无法更新作者');
    }
  }

  remove(id: number) {
    return `This action removes a #${id} author`;
  }
}
